package com.qkjia.java8;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

import org.junit.Test;

public class TestForkJoin {
	
	@Test
	public void test1(){
		long start = System.currentTimeMillis();

		// ForkJoinPool 用于运行ForkJoinTask的ExecutorService 。
		// ForkJoinPool为来自非ForkJoinTask客户端的提交以及管理和监控操作提供了入口点。
		ForkJoinPool pool = new ForkJoinPool();
		// ForkJoinTask 在ForkJoinPool中运行的任务的抽象基类
		ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 10000000000L);
		
		long sum = pool.invoke(task);
		System.out.println(sum);
		
		long end = System.currentTimeMillis();
		
		System.out.println("耗费的时间为: " + (end - start)); // 112-1953-1988-2654-2647-20663-113808
	}
	
	@Test
	public void test2(){
		long start = System.currentTimeMillis();
		
		long sum = 0L;
		
		for (long i = 0L; i <= 10000000000L; i++) {
			sum += i;
		}
		
		System.out.println(sum);
		
		long end = System.currentTimeMillis();
		
		System.out.println("耗费的时间为: " + (end - start)); // 34-3174-3132-4227-4223-31583
	}
	
	@Test
	public void test3(){
		long start = System.currentTimeMillis();

		// LongStream. 支持顺序和并行聚合操作的原始长值元素序列。 这是Stream的long原始特化。
		// .rangeClosed(0L, 10000000000L) 以1的增量步长返回从startInclusive 包含到endInclusive（包含）的顺序有序LongStream
		Long sum = LongStream.rangeClosed(0L, 10000000000L)
							 .parallel()
							 .sum();
		
		System.out.println(sum);
		
		long end = System.currentTimeMillis();
		
		System.out.println("耗费的时间为: " + (end - start)); //2061-2053-2086-18926
	}

}
